package com.ffzx.commerce.framework.utils;

import java.util.Set;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.jasig.cas.client.util.AssertionHolder;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import com.ffzx.commerce.framework.constant.RedisPrefix;
import com.ffzx.commerce.framework.system.entity.SysUser;

/**
 * Redis数据存储
 * 
 * @author CMM
 *
 * 2016年3月16日 上午9:48:53
 */
@Component
@Lazy(false)
public class RedisWebUtils {
	
	@Resource
	private RedisUtil redisUtil;
	
	private static RedisUtil redisService;
	
	@PostConstruct
	public void init(){
		RedisWebUtils.redisService = redisUtil;
	}
	
	/**
	 * 删除用户登录在Redis中缓存的信息
	 */
	public static void removeRedisSystemLogin(){
		SysUser currentUser = RedisWebUtils.getLoginUser();
		if(null != currentUser){
			redisService.remove(RedisPrefix.SYSTEM_LOGIN + RedisPrefix.USER_MENU + currentUser.getId());
		}
		
		redisService.remove(RedisPrefix.SYSTEM_LOGIN + RedisPrefix.USER_PERMISSION + AssertionHolder.getAssertion().getPrincipal().getName());
		redisService.remove(RedisPrefix.SYSTEM_LOGIN + RedisPrefix.USER + AssertionHolder.getAssertion().getPrincipal().getName());
	}
	
	/**
	 * 设置登录用户
	 * @param sysUser
	 */
	public static void setLoginUser(SysUser sysUser){
		redisService.set(RedisPrefix.SYSTEM_LOGIN + RedisPrefix.USER + AssertionHolder.getAssertion().getPrincipal().getName(), sysUser);
	}
	
	/**
	 * 得到登录用户
	 * @return
	 */
	public static SysUser getLoginUser(){
		return (SysUser)redisService.get(RedisPrefix.SYSTEM_LOGIN + RedisPrefix.USER + AssertionHolder.getAssertion().getPrincipal().getName());
	}
	
	/**
	 * 设置权限
	 * @param request
	 * @param permission
	 */
	public static void setPermission(Set<String> permission){
		redisService.set(RedisPrefix.SYSTEM_LOGIN + RedisPrefix.USER_PERMISSION + AssertionHolder.getAssertion().getPrincipal().getName(), permission);
	}
	
	/**
	 * 获取权限
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Set<String> getPermission(){
		return (Set<String>)redisService.get(RedisPrefix.SYSTEM_LOGIN + RedisPrefix.USER_PERMISSION + AssertionHolder.getAssertion().getPrincipal().getName());
	}
	
}
